
import React, {useState, useEffect, useMemo} from 'react';
import { to_float, obj_float, KInput, useKForm, WaitUmd, is_empty, Btn, obj_str, loc, PanelFind, Ret, Title, filter_row,
    uJob, cline, show_mt, save_data, d_sort, InfoDlg, ck_float, useCmd, useHigh, GridTable } from 'sui';
import { reload, load_col } from './cmd';
import { BindView } from '../../goods/task/bind';

const PsnView = ({ cur, hreturn, no_acc }) => {
    const [main, setMain] = useState();
    const [col, setCol] = useState();
    const [cur_num, curNum] = useState(0);
    const [row, setRow] = useState();
    const [open_info, openInfo] = useState(false);
    const [high] = useHigh(280, 100);
    const umd = useCmd();
    const form = useKForm();

    useEffect(() => {
        load_col(setCol);

        reload(null, cur, (v) => {
            setMain(v);
            setRow(v);
            curNum(v ? v.length : 0);
        }, cur);
    }, [cur]);

    const getRow = useMemo(() => {
        if (is_empty(col)) {
            return null;
        }

        const lst = col.map(d => d.sn);
        return filter_row(row, lst, umd.filter);
    }, [row, umd.filter, col]);

    const getCol = useMemo(() => {
        if (is_empty(col)) {
            return null;
        }

        const tmp = [
            {name: loc("l_193"), key: 'index', width: 70, frozen: true},
        ];

        col.forEach(d => show_mt(tmp, d, 110));

        return tmp;
    }, [col]);

    const ck_empty_float = (v, k1) => {
        const kv = form.get(k1);
        if (!v && !kv) {
            return null;
        }

        return ck_float(v);
    };

    const ck_range_float = (v, k1) => {
        const kv = form.get(k1);
        if (!v && !kv) {
            return null;
        }

        const a = to_float(kv);
        const b = to_float(v);

        if (b < a) {
            return loc("l_705");
        }
    };

    const getRange = (k1, k2) => {
        let min = form.get(k1);
        let max = form.get(k2);

        if (!min || !max) {
            return [false, null, null];
        }

        return [true, to_float(min), to_float(max)];
    };

    const isIn = (v, a, b) => {
        const kv = Math.trunc(v * 1000);
        const ka = Math.trunc(a * 1000);
        const kb = Math.trunc(b * 1000);

        return (kv >= ka && kv <= kb);
    };

    const hFind = (data) => {
        if (is_empty(data)) {
            setRow(null);
            curNum(0);
            return;
        }

        const ck = {
            dmin: v => ck_empty_float(v, "dmin"),
            dmax: v => ck_range_float(v, "dmin"),
            kmin: v => ck_empty_float(v, "kmin"),
            kmax: v => ck_range_float(v, "kmin"),
            bmin: v => ck_empty_float(v, "bmin"),
            bmax: v => ck_range_float(v, "bmin"),
            wmin: v => ck_empty_float(v, "wmin"),
            wmax: v => ck_range_float(v, "wmin"),
            amin: v => ck_empty_float(v, "amin"),
            amax: v => ck_range_float(v, "amin"),
            fmin: v => ck_empty_float(v, "fmin"),
            fmax: v => ck_empty_float(v, "fmin"),
            gmin: v => ck_range_float(v, "gmin"),
            gmax: v => ck_range_float(v, "gmin"),
        };

        if (form.isErr(ck)) {
            return;
        }

        const [is_dmin, dmin, dmax] = getRange("dmin", "dmax");
        const [is_kmin, kmin, kmax] = getRange("kmin", "kmax");
        const [is_bmin, bmin, bmax] = getRange("bmin", "bmax");
        const [is_wmin, wmin, wmax] = getRange("wmin", "wmax");
        const [is_amin, amin, amax] = getRange("amin", "amax");
        const [is_fmin, fmin, fmax] = getRange("fmin", "fmax");
        const [is_gmin, gmin, gmax] = getRange("gmin", "gmax");

        if (!is_dmin && !is_kmin && !is_bmin && !is_wmin && !is_amin && !is_fmin && !is_gmin) {
            const val = [...data];
            d_sort(val, "boxaway");
            val.forEach((d, i) => d["index"] = i + 1);

            setRow(val);
            curNum(val ? val.length : 0);
            return;
        }

        const ret = data.filter(d => {
            const outdia = obj_float(d, "outdia");
            const india = obj_float(d, "india");
            const standout = obj_float(d, "standout");
            const angle = obj_float(d, "angle");

            if (is_gmin && !isIn(angle, gmin, gmax)) {
                return false;
            }

            if (is_fmin) {
                const standout = obj_float(d, "standout");
                const dent = obj_float(d, "dent");

                const w = Math.abs(standout - dent);

                if (!isIn(w, fmin, fmax)) {
                    return false;
                }
            }

            if (is_amin) {
                const w = Math.abs(outdia - india);

                if (!isIn(w, amin, amax)) {
                    return false;
                }
            }

            if (is_wmin) {
                const outwidth = obj_float(d, "outwidth");
                const inwidth = obj_float(d, "inwidth");
                const w = Math.abs(outwidth - inwidth);

                if (!isIn(w, wmin, wmax)) {
                    return false;
                }
            }

            if (is_dmin && !isIn(outdia, dmin, dmax)) {
                return false;
            }

            if (is_kmin && !isIn(india, kmin, kmax)) {
                return false;
            }

            if (is_bmin && !isIn(standout, bmin, bmax)) {
                return false;
            }

            return true;
        });


        d_sort(ret, "boxaway");
        ret.forEach((d, i) => d["index"] = i + 1);

        setRow(ret);
        curNum(ret ? ret.length : 0);
    };

    const doTask = (val) => {
        if (is_empty(val)) {
            return;
        }

        umd.startWait();

        uJob(null, "away/pure",
            {
                line: cline(),
                k: obj_str(cur, "sn"),
                v: val,
            },
            r => {
                reload(umd.endWait, cur, (v) => {
                    setMain(v);
                    hFind(v);

                    openInfo(true);
                }, cur);
            },
            e => umd.setErr(), true);
    };

    const hBind = (v) => {
        umd.hreturn();
        doTask(v);
    };

    if (umd.isFin("bind")) {
        return <BindView hreturn={umd.hreturn} main={row} cur={cur} hcmd={hBind} title={loc("l_888")} col={getCol}/>;
    }

    const hout = () => {
        save_data(main, getCol, loc("l_818"), umd);
    };

    const Right = () => (
        <div className="inline-flex">
            <Btn hcmd={() => umd.pact(null, null, "bind")} color="teal" disabled={no_acc("mb")}>{loc("l_888")}</Btn>
            <Btn className="ml-4" hcmd={hout} color="green">{loc("l_298")}</Btn>
            <Ret className="ml-4" hcmd={hreturn}/>
        </div>
    );

    const Left = () => (
        <div className="inline-flex items-center">
            <Title mod={obj_str(cur, "sn")} sub={loc("l_887")}>{loc("l_818")}</Title>
            <div className="ml-10 bg-teal-300 px-3 pt-2 pb-1">{loc("l_127")}<span className="ml-6">{cur_num}</span></div>
        </div>
    );

    return (
        <div className="flex flex-col">
            <PanelFind left={<Left/>} right={<Right/>} hcmd={umd.setFilter}>
                <div className="flex flex-row">
                    <Btn className="mr-4 mb-6 mt-2" hcmd={() => hFind(main)} color="teal">{loc("l_832")}</Btn>
                    <div className="flex flex-col mb-4">
                        <div className="inline-flex items-center">
                            <div className="inline-flex items-center px-2 border-blue-600 border">
                                <span className="text-base mr-4 mt-1">{`${loc("l_690")} ( D )`}</span>
                                <KInput label={loc("l_696")} form={form} name="dmin" mg="dense" width="w-20"/>
                                <KInput label={loc("l_646")} form={form} name="dmax" mg="dense" width="w-20" className="ml-2"/>
                            </div>
                            <div className="inline-flex items-center px-2 ml-4 border-blue-600 border">
                                <span className="text-base mr-4 mt-1">{`${loc("l_691")} ( d )`}</span>
                                <KInput label={loc("l_696")} form={form} name="kmin" mg="dense" width="w-20"/>
                                <KInput label={loc("l_646")} form={form} name="kmax" mg="dense" width="w-20" className="ml-2"/>
                            </div>
                            <div className="inline-flex items-center px-2 ml-4 border-blue-600 border">
                                <span className="text-base mr-4 mt-1">{`${loc("l_743")} ( b )`}</span>
                                <KInput label={loc("l_696")} form={form} name="bmin" mg="dense" width="w-20"/>
                                <KInput label={loc("l_646")} form={form} name="bmax" mg="dense" width="w-20" className="ml-2"/>
                            </div>
                            <div className="inline-flex items-center px-2 ml-4 border-blue-600 border">
                                <span className="text-base mr-4 mt-1">{loc("l_170")}</span>
                                <KInput label={loc("l_696")} form={form} name="gmin" mg="dense" width="w-20"/>
                                <KInput label={loc("l_646")} form={form} name="gmax" mg="dense" width="w-20" className="ml-2"/>
                            </div>
                        </div>
                        <div className="inline-flex mt-4 items-center">
                            <div className="inline-flex items-center px-2 border-blue-600 border">
                                <span className="text-base mr-4 mt-1">{loc("l_692")}</span>
                                <KInput label={loc("l_696")} form={form} name="wmin" mg="dense" width="w-20"/>
                                <KInput label={loc("l_646")} form={form} name="wmax" mg="dense" width="w-20" className="ml-2"/>
                            </div>
                            <div className="inline-flex items-center px-2 border-blue-600 border ml-4">
                                <span className="text-base mr-4 mt-1">{loc("l_167")}</span>
                                <KInput label={loc("l_696")} form={form} name="amin" mg="dense" width="w-20"/>
                                <KInput label={loc("l_646")} form={form} name="amax" mg="dense" width="w-20" className="ml-2"/>
                            </div>
                            <div className="inline-flex items-center px-2 border-blue-600 border ml-4">
                                <span className="text-base mr-4 mt-1">{loc("l_168")}</span>
                                <KInput label={loc("l_696")} form={form} name="fmin" mg="dense" width="w-20"/>
                                <KInput label={loc("l_646")} form={form} name="fmax" mg="dense" width="w-20" className="ml-2"/>
                            </div>
                            <Btn className="ml-4" hcmd={() => form.clear_all()}>{loc("l_543")}</Btn>
                        </div>
                    </div>
                </div>
            </PanelFind>
            <GridTable high={high} col={getCol} row={getRow}/>
            <InfoDlg open={open_info} setOpen={openInfo} msg={loc("l_825")} hcmd={() => umd.endWait()}/>
            <WaitUmd umd={umd}/>
        </div>
    );
};

export {PsnView};
